#ifndef APPUPDATER_H
#define APPUPDATER_H

#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QObject>
#include <QString>
#include <QUrl>

class AppUpdater : public QObject
{
    Q_OBJECT

public:
    explicit AppUpdater(const QString& appId, const QString& currentVersion,
                        QObject* parent = nullptr);
    ~AppUpdater();

    void checkForUpdates();
    void startDownload(const QString& downloadUrlStr);  // New public method
    void cancelDownload();                              // ADDED: Method to cancel ongoing download
    void installUpdate();
signals:
    // 检查结果信号
    void updateCheckFinished(bool updateAvailable, const QString& latestVersion,
                             const QString& downloadUrl, const QString& releaseNotes);
    void updateStatusMessage(const QString& message);  // 用于向UI传递状态信息
    void errorOccurred(const QString& errorMessage);

    // 下载相关信号
    void downloadStarted(const QString& fileName);
    void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
    void downloadFinished(const QString& filePath, bool success, const QString& errorString);
    void readyToQuitForUpdate();  // ADDED: Signal to indicate updater launched and app can quit

private slots:
    void onUpdateCheckReplyFinished(QNetworkReply* reply);

    // Slots for download handling
    void onDownloadReadyRead();
    void onDownloadProgressSlot(qint64 bytesReceived, qint64 bytesTotal);
    void onDownloadFinishedSlot();

private:
    void loadOrInitializeUpdateUrl();

    QNetworkAccessManager* m_networkManager;
    QString m_appId;
    QString m_currentVersion;
    QString m_updateCheckUrlBase;

    // Download related members
    QNetworkReply* m_downloadReply;
    QFile* m_downloadedFile;
    QString m_targetFilePath;  // Full path where the download will be saved

    // ADDED: Default URL constant
    static const QString DEFAULT_UPDATE_URL;
};

#endif  // APPUPDATER_H